import React, { useRef, useState, useEffect } from 'react';
import styles from './index.module.less';
import Tabs from '@/components/tabs';
import { MyMatterList, AllowMatterList } from '@/services/official-doc';
import ApproveCard from '@/components/card';
import { Link, Prompt } from 'react-router-dom';
import { PrintNum } from '@/utils';
import { useRefreshList } from '@/hooks/use-refresh-list';
import EmptyRefresh from '@/components/empty/empty-refresh';
import AntdRefreshList from '@/components/antd-refresh-list';
import EmptyLoading from '@/components/empty/empty-loading';

// 视窗高度减去减去头部和底部组件的高度
const height =
  document.documentElement.clientHeight -
  (document.documentElement.clientWidth * (40 + 50 + 5)) / 375;
const defaultPageSize = 10;

export enum MENU_TYPE {
  MY_IN_CHARGE_OF = 1,
  MY_AUTHORZED = 2,
}

const OfficialDoc: React.FC<any> = (props) => {
  const menu = useRef([
    { text: '我负责的事项', value: MENU_TYPE.MY_IN_CHARGE_OF },
    { text: '授权我的事项', value: MENU_TYPE.MY_AUTHORZED }
  ]);

  const [pageSize, setPageSize] = useState(defaultPageSize);

  const {
    showDom,
    refreshing,
    loadingMore,
    dataSource,
    searchData,
    setDatasource,
    handleRefresh,
    handleLoadMore,
    handleSearch,
    routeWillLeave
  } = useRefreshList({
    routeProps: props,
    initSearchData: { type: 1 }, // 待审批 1 已审批 2
    cacheRouteList: ['/official-doc/matter-detail'],
    pullData: async (options) => {
      const { params, setLastId, setSurplusTotal, setData } = options;
      console.log(params?.pageNum);
      const reqParams = {
        lastId: params.lastId,
        pageSize: params?.pageNum
          ? PrintNum(params?.pageNum * defaultPageSize)
          : defaultPageSize,
        searchType: params?.type
      };
      const RequestData = params?.type === 1 ? MyMatterList : AllowMatterList;
      const res = await RequestData(reqParams);
      const list = formatData(res.data?.rows) || [];
      setSurplusTotal(res.data?.total ?? 0);
      setPageSize(
        params?.pageNum
          ? PrintNum(params?.pageNum * defaultPageSize)
          : defaultPageSize
      );
      setData(params?.lastId ? dataSource.concat(list) : list);
      setLastId(list[list.length - 1]?.id);
    }
  });

  const formatData = (data: any[]): any => {
    data?.forEach((item) => {
      const matterTotalText =
        item.matterTotal === -1 || (!item.matterTotal && item.matterTotal !== 0) ? '不限额' : item.matterTotal || '无';
      item.formData = [
        { label: '经办人', value: item.managerName || '无' },
        { label: '总金额', value: matterTotalText }
      ];
      item.cardTitle = item.matterName;
    });
    return data;
  };

  return (
    <div className={styles['wrap']}>
      <Tabs
        data={menu.current}
        dataType={searchData?.type}
        onChange={(val) => handleSearch({ type: val })}
      />
      {showDom ? (
        <div className={styles.cardList}>
          {dataSource?.length > 0 ? (
            <AntdRefreshList
              height={height}
              initialListSize={pageSize}
              dataSource={dataSource}
              refreshing={refreshing}
              loadingMore={loadingMore}
              renderRow={(item, sectionID, index) => (
                <div className={styles.cardItem} key={index}>
                  <Link
                    to={`/official-doc/matter-detail/${item.id}?type=${searchData.type}`}
                  >
                    <ApproveCard data={item} matter></ApproveCard>
                  </Link>
                </div>
              )}
              onRefresh={handleRefresh}
              onEndReached={handleLoadMore}
            />
          ) : (
            <EmptyRefresh refreshing={refreshing} onRefresh={handleRefresh} />
          )}
        </div>
      ) : (
        <EmptyLoading />
      )}
      <Prompt message={routeWillLeave} />
    </div>
  );
};

export default OfficialDoc;
